<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>
    <BasicTable title="教师列表" titleTooltip="关注嘉然顿顿解馋" :columns="columns" :request="loadDataTable"
      :row-key="(row) => row.id" ref="actionRef" :actionColumn="actionColumn" :scroll-x="1360"
      @update:checked-row-keys="onCheckedRow">
      <template #tableTitle>
        <n-button type="primary" @click="addTable">
          <template #icon>
            <n-icon>
              <PlusOutlined />
            </n-icon>
          </template>
          新建
        </n-button>
      </template>
      <template #toolbar>
        <n-button type="primary" @click="reloadTable">刷新数据</n-button>
      </template>
    </BasicTable>
    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="modalTitle">
      <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="80" class="py-4">
        <n-form-item label="工号" path="TID">
          <n-input placeholder="请输入工号" v-model:value="formParams.TID" />
        </n-form-item>
        <n-form-item label="姓名" path="name">
          <n-input placeholder="请输入名称" v-model:value="formParams.name" />
        </n-form-item>
        <n-form-item label="职务" path="job">
          <n-select v-model:value="formParams.job" :options="[{label:'教师',value:'1'},{label:'档案管理员',value:'0'}]" />
        </n-form-item>
        <n-form-item label="学院" path="academyID">
          <n-select v-model:value="formParams.academyID" :options="academyOptions"></n-select>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="() => (
            showModal = false,
            formParams['TID'] = null,
            formParams['name'] = null,
            formParams['job'] = null,
            formParams['academyID'] = null
          )">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>

  </n-card>
</template>

<script lang="ts" setup>
import { reactive, ref, h, onMounted } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { getTableList } from '@/api/manager/teacherManage/list';
import { columns } from './teacherColumns';
import { SelectOption, useDialog, useMessage } from 'naive-ui';
import { PlusOutlined } from '@vicons/antd';
import { http } from '@/utils/http/axios';

const modalTitle = ref('新建');
const showModal = ref(false);
const formBtnLoading = ref(false);
const formRef: any = ref(null);
const message = useMessage();
const dialog = useDialog();
const actionRef = ref();
const modalUrl = ref('');

const rules = {
  TID: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入工号',
  },
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入姓名',
  },
  job: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择职务',
  },
  academyID: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择学院',
  }

}

const formParams = reactive(
  {
    TID: null,
    name: null,
    job: null,
    academyID : null
  }
)
const params = reactive({
  pageSize: 10,
});

const actionColumn = reactive({
  width: 150,
  title: '操作',
  key: 'action',
  fixed: 'right',
  align: 'center',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: createActions(record),
    });
  },
});

function createActions(record) {
  return [
    {
      label: '删除',
      icon: 'ic:outline-delete-outline',
      onClick: handleDelete.bind(null, record),
      // 根据业务控制是否显示 isShow 和 auth 是并且关系
      ifShow: () => {
        return true;
      },
      // 根据权限控制是否显示: 有权限，会显示，支持多个
      auth: ['basic_list'],
    },
    {
      label: '修改',
      onClick: handleEdit.bind(null, record),
      ifShow: () => {
        return true;
      },
      auth: ['basic_list'],
    },
  ];
}

const loadDataTable = async (res) => {
  return await getTableList({ ...params, ...res });
};

function onCheckedRow(rowKeys) {
  
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

function handleDelete(record) {
  console.log(record);
  dialog.info({
    title: '提示',
    content: `您想删除${record.name}`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      http.request({
        url: '/manager/teacher_manage/deleteTeacher',
        method: 'get',
        params:{TID:record['TID']}
      }).then(
        () => {
          message.success('删除成功');
          reloadTable();
        }
      );
      
    },
    onNegativeClick: () => { },
  });
}

function handleEdit(record) {
  console.log(record);
  formParams['TID'] = record['TID'];
  formParams['name'] = record['name'];
  formParams['job'] = record['job'].toString();
  formParams['academyID'] = record['academyID'].toString();
  modalTitle.value = "修改";
  modalUrl.value = '/manager/teacher_manage/editTeacher';
  showModal.value = true;
  //message.success('您点击了编辑按钮');
}

const academyOptions = ref<SelectOption[]>([]);

onMounted(
  async () => {
    const academyMajorInfo = ref();
    academyMajorInfo.value = await http.request({
      url: '/manager/academy_major_manage/list',
      method: 'get',
    });
    academyMajorInfo.value.forEach(element => {
      academyOptions.value.push({
        label: element['academyName'],
        value: element['academyID'].toString()
      });
    });
    //获取学院信息
  })

const schemas: FormSchema[] = [
  {
    field: 'TID',
    component: 'NInputNumber',
    label: '工号',
    componentProps: {
      placeholder: "请输入工号",
      showButton: false
    }
  }, {
    field: 'academyID',
    component: 'NSelect',
    label: '学院',
    componentProps: {
      placeholder: '请选择学院',
      //remote:true,
      value: ref(null),
      options: academyOptions,
    }
  },{
    field: 'job',
    component: 'NSelect',
    label: '职务',
    componentProps: {
      placeholder: '请选择职务',
      //remote:true,
      value: ref(null),
      options: [
        {
          'label' : '教师',
          'value' : '1'
        },{
          'label' : '档案管理员',
          'value' : '0'
        }
      ],
    }
  },
]

const [register] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:4 xl:5 2xl:5' },
  labelWidth: 80,
  schemas,
});

function addTable() {
  modalTitle.value = '新建';
  modalUrl.value ='/manager/teacher_manage/addTeacher';
  showModal.value = true;
}

function confirmForm(e) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate((errors) => {
    if (!errors) {
      //message.success('新建成功');
      let params = formParams;
      http.request({
        url: modalUrl.value,
        method: 'post',
        params
      }).then(
        () => {
          message.success('成功');
          showModal.value = false;
          formParams['TID'] = null,
          formParams['name'] = null,
          formParams['job'] = null,
          formParams['academyID'] = null
          reloadTable();
        }
      );
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}


function handleSubmit(values: Recordable) {
  params['academyID'] = values['academyID'];
  params['TID'] = values['TID'];
  params['job'] = values['job'];
  reloadTable();
}

function handleReset(values: Recordable) {
  console.log(values);
  reloadTable();
}

</script>

<style lang="less" scoped>
</style>
